package cn.spring.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.spring.bean.Address;
import cn.spring.bean.Commodity;
import cn.spring.bean.Employee;
import cn.spring.bean.Orders;
import cn.spring.bean.Shoppingcart;
import cn.spring.bean.Today;
import cn.spring.service.AddressService;
import cn.spring.service.OrdersService;
import cn.spring.service.ShoppingcartService;
import cn.spring.util.WordUtil;

@Controller
@RequestMapping("/shop")
public class ShoppingcartController {
	@Autowired
	private ShoppingcartService biz;
	
	@Autowired
	private AddressService aBiz;
	
	@Autowired
	private OrdersService oBiz;
	
	@RequestMapping("/addCom")
	public String addCom(HttpServletRequest request,Model model,@RequestParam("id")String id,@RequestParam("num")String num){
		Employee emp=(Employee)request.getSession().getAttribute("emp");
		if(id==null||id.equals("")||id.length()==0||id.equals("null")){
			model.addAttribute("login", emp);
			Map<String, Object> map=new LinkedHashMap<String, Object>();
			List<Orders> list=oBiz.selectByState(emp.getId());
			for(Orders order:list){
				List<Map<String, Object>> list1=biz.selectByState(emp.getId(),order.getId());
				map.put(order.getId()+"", list1);
			}
			model.addAttribute("shangMap", map);
			return "../order";
		}
		int count=aBiz.addressCount(emp.getId());
		if(count>0){
			Address add=aBiz.selectMo(emp.getId());
			Orders ord=new Orders();
			ord.setAddressId(add.getId());
			ord.setEmpId(emp.getId());
			ord.setState(1);
			ord.setTime(null);
			oBiz.save(ord);
			if(ord.getId()!=null){
				if(biz.save(id, num, emp,ord.getId())){
					Map<String, Object> map=new LinkedHashMap<String, Object>();
					List<Orders> list=oBiz.selectByState(emp.getId());
					for(Orders order:list){
						List<Map<String, Object>> list1=biz.selectByState(emp.getId(),order.getId());
						map.put(order.getId()+"", list1);
					}
					model.addAttribute("shangMap", map);
					return "../order";
				}else{
					return "../error";
				}
			}else{
				return "../error";
			}
		}else{
			return "../addAddress";
		}
	}
	
	@RequestMapping("/today")
	public String today(Model model){
		Map<Today, List<Map<String, Object>>> list=biz.today();
		Double total=0.0;
		Iterator<Map.Entry<Today, List<Map<String, Object>>>> it = list.entrySet().iterator();
		while (it.hasNext()) {
		   Map.Entry<Today, List<Map<String, Object>>> entry = it.next();
		   Today to=(Today)entry.getKey();
		   total+=to.getTotal();
		 }
		model.addAttribute("today", list);
		model.addAttribute("total", total);
		model.addAttribute("comList", biz.toDayCommodity());
		return "../admin/index";
	}
	
	//后台今日订单搜索清单功能
	@RequestMapping("/todayByWord")
	public String today(Model model,@RequestParam("word")String word) throws UnsupportedEncodingException{
		word = URLDecoder.decode(word , "UTF-8");
		Map<Today, List<Map<String, Object>>> list=biz.toDayByKey(word);
		Double total=0.0;
		Iterator<Map.Entry<Today, List<Map<String, Object>>>> it = list.entrySet().iterator();
		while (it.hasNext()) {
		   Map.Entry<Today, List<Map<String, Object>>> entry = it.next();
		   Today to=(Today)entry.getKey();
		   total+=to.getTotal();
		 }
		model.addAttribute("today", list);
		model.addAttribute("total", total);
		model.addAttribute("comList", biz.toDayCommodityByWord(word));
		return "../admin/index";
	}
	
	@RequestMapping("/queren")
	public String queren(@RequestParam("id")int id,Model model){
		int count=biz.queren(id);
		if(count>0){
			Map<Today, List<Map<String, Object>>> list=biz.today();
			Double total=0.0;
			Iterator<Map.Entry<Today, List<Map<String, Object>>>> it = list.entrySet().iterator();
			while (it.hasNext()) {
			   Map.Entry<Today, List<Map<String, Object>>> entry = it.next();
			   Today to=(Today)entry.getKey();
			   total+=to.getTotal();
			 }
			model.addAttribute("today", list);
			model.addAttribute("total", total);
			model.addAttribute("comList", biz.toDayCommodity());
			return "../admin/index";
		}else{
			return "../admin/error";
		}
	}
	
	@RequestMapping("/createWord")
	public void  createWord(HttpServletRequest request,HttpServletResponse res) {
		 /** 用于组装word页面需要的数据 */
        Map<String, Object> dataMap = new HashMap<String, Object>();
        
        /** 组装数据 */
        List<Today> list=biz.today1();
        List<Today> list1=new ArrayList<Today>();
      //遍历map中的键  
        
      for (Today to : list) {  
    	to.setShangList(biz.getShang(to.getOrdid()));
        list1.add(to);
      }  
        dataMap.put("today", list1);
      
        /** 文件名称，唯一字符串 */
        Random r=new Random();
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
        StringBuffer sb=new StringBuffer();
        sb.append(sdf1.format(new Date()));
        sb.append("_");
        sb.append(r.nextInt(100));
        
        //文件路径
       // String filePath=request.getSession().getServletContext().getRealPath("upload");  
        String filePath="C:\\upload";  
        //文件唯一名称
        String fileOnlyName = sb+"清单.doc";
        
        //文件名称
        String fileName="Word文档.doc";
        OutputStream os = null;
        try {
        /** 生成word */
        WordUtil.createWord(dataMap, "today.ftl", filePath, fileOnlyName);
        
      
            //解决中文乱码
            filePath = URLDecoder.decode(filePath, "UTF-8");
            fileOnlyName = URLDecoder.decode(fileOnlyName, "UTF-8");
            fileName = URLDecoder.decode(fileName, "UTF-8");
            
            //如果文件不存在，则会跳入异常，然后可以进行异常处理
              // new FileInputStream(filePath + File.separator +  fileOnlyName);
        
       
            
            os = res.getOutputStream();
            res.reset();
            res.setHeader("Content-Disposition", "attachment; filename="+fileOnlyName);
            res.setContentType("application/octet-stream; charset=utf-8");
            File targetFile = new File(filePath, fileOnlyName);  
            os.write(FileUtils.readFileToByteArray(targetFile));
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        }
        
	}
	
	@RequestMapping("/createWordNum")
	public void  createWordNum(HttpServletRequest request,HttpServletResponse res) {
		 /** 用于组装word页面需要的数据 */
        Map<String, Object> dataMap = new HashMap<String, Object>();
        
        /** 组装数据 */
        List<Map<String, Object>> list=biz.toDayCommodity();
       
        dataMap.put("today", list);
      
        /** 文件名称，唯一字符串 */
        Random r=new Random();
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
        StringBuffer sb=new StringBuffer();
        sb.append(sdf1.format(new Date()));
        sb.append("_");
        sb.append(r.nextInt(100));
        
        //文件路径
       // String filePath=request.getSession().getServletContext().getRealPath("upload");  
        String filePath="C:\\upload";  
        //文件唯一名称
        String fileOnlyName = sb+"清单.doc";
        
        //文件名称
        String fileName="Word文档.doc";
        OutputStream os = null;
        try {
        /** 生成word */
        WordUtil.createWord(dataMap, "todayNum.ftl", filePath, fileOnlyName);
        
      
            //解决中文乱码
            filePath = URLDecoder.decode(filePath, "UTF-8");
            fileOnlyName = URLDecoder.decode(fileOnlyName, "UTF-8");
            fileName = URLDecoder.decode(fileName, "UTF-8");
            
            //如果文件不存在，则会跳入异常，然后可以进行异常处理
              // new FileInputStream(filePath + File.separator +  fileOnlyName);
        
       
            
            os = res.getOutputStream();
            res.reset();
            res.setHeader("Content-Disposition", "attachment; filename="+fileOnlyName);
            res.setContentType("application/octet-stream; charset=utf-8");
            File targetFile = new File(filePath, fileOnlyName);  
            os.write(FileUtils.readFileToByteArray(targetFile));
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        }
        
	}
	
	
	@RequestMapping("/exportExcel")
	public void exportExcel(HttpServletRequest request,HttpServletResponse response) { 
        HSSFWorkbook workbook = null;  
        HSSFSheet sheet = null;  
        List<Map<String, Object>> accounts=biz.findAccounts();
        FileOutputStream out = null;
        // 保存文件的路径  
        String realPath = (getSispPath(request) + "/files");  
        // 新的文件名  
        String newFileName = "送货单" + System.currentTimeMillis() + ".xls";
        try { 
        	workbook = new HSSFWorkbook();  
            out = new FileOutputStream(realPath+"/"+newFileName);  
        	for (Map<String, Object> account : accounts) {
        		
        		if(account!=null) {
        			List<Map<String, Object>> list=biz.finGoodsByOId(Integer.parseInt(account.get("id").toString()));
	        		sheet=workbook.createSheet(account.get("name")==null?"1":account.get("name").toString()+account.get("id"));
	        		if (sheet != null) {  
	                    	HSSFRow rowHead=sheet.createRow(0);
	                    	rowHead.setHeight((short)(21*20));
	                    	HSSFCell cellHead = rowHead.createCell(0);
	                    	HSSFCellStyle styleBorder = workbook.createCellStyle();
	                    	styleBorder.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中  
	                    	styleBorder.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
	                    	styleBorder.setBorderBottom(HSSFCellStyle.BORDER_THIN);
	                        styleBorder.setBorderLeft(HSSFCellStyle.BORDER_THIN);
	                        styleBorder.setBorderRight(HSSFCellStyle.BORDER_THIN);
	                        styleBorder.setBorderTop(HSSFCellStyle.BORDER_THIN);
	                        styleBorder.setLocked(true);  
	                        styleBorder.setWrapText(true); 
	                    	CellRangeAddress region0 = new CellRangeAddress(0,0,(short)0,(short)9);
	                        sheet.addMergedRegion(region0);
	                    	cellHead.setCellValue("包有帮餐饮管理有限公司送货单");
	                    	cellHead.setCellStyle(styleBorder);
	                    	rowHead=sheet.createRow(1);
	                    	rowHead.setHeight((short)(21*20));
	                    	CellRangeAddress region1 = new CellRangeAddress(1,1,(short)0,(short)1);
	                        sheet.addMergedRegion(region1);
	                        
	                    	rowHead.createCell(0).setCellValue("客户名字:");
	                    	rowHead.getCell(0).setCellStyle(styleBorder);
	                    	rowHead.createCell(2).setCellValue(account.get("name").toString());
	                    	rowHead.getCell(2).setCellStyle(styleBorder);
	                    	
	                    	//rowHead.setRowStyle(styleBorder);
	                    	/*CellRangeAddress region2 = new CellRangeAddress(1,1,(short)5,(short)6);
	                        sheet.addMergedRegion(region2);*/
	                        rowHead.createCell(5).setCellValue("联系人");
	                    	rowHead.getCell(5).setCellStyle(styleBorder);
	                    	rowHead.createCell(6).setCellValue("刘小姐");
	                    	rowHead.getCell(6).setCellStyle(styleBorder);
	                    	rowHead.createCell(8).setCellValue("编号");
	                    	rowHead.getCell(8).setCellStyle(styleBorder);
	                    	rowHead.createCell(9).setCellValue("NO"+account.get("id").toString());
	                    	rowHead.getCell(9).setCellStyle(styleBorder);
	                    	
	                    	rowHead=sheet.createRow(2);
	                    	rowHead.setHeight((short)(19.5*20));
	                    	CellRangeAddress region3 = new CellRangeAddress(2,2,(short)0,(short)1);
	                        sheet.addMergedRegion(region3);
	                        rowHead.createCell(0).setCellValue("联系电话:");
	                    	rowHead.getCell(0).setCellStyle(styleBorder);
	                    	rowHead.createCell(2).setCellValue(account.get("phone").toString());
	                    	rowHead.getCell(2).setCellStyle(styleBorder);
	                    	/*rowHead.createCell(4).setCellValue("地址：");
	                    	rowHead.getCell(4).setCellStyle(styleBorder);*/
	                    	
	                    	CellRangeAddress region4 = new CellRangeAddress(2,2,(short)6,(short)7);
	                        sheet.addMergedRegion(region4);
	                        rowHead.createCell(5).setCellValue("地址：");
	                    	rowHead.getCell(5).setCellStyle(styleBorder);
	                    	rowHead.createCell(6).setCellValue(account.get("address").toString());
	                    	rowHead.getCell(6).setCellStyle(styleBorder);
	                    	rowHead.createCell(8).setCellValue("日期：");
	                    	rowHead.getCell(8).setCellStyle(styleBorder);
	                    	Date date = new Date(); 
	                    	DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); 
	                    	String dateFormat = df.format(date); 
	                    	rowHead.createCell(9).setCellValue(dateFormat);
	                    	rowHead.getCell(9).setCellStyle(styleBorder);
	                    	
	                    	rowHead=sheet.createRow(3);
	                    	rowHead.setHeight((short)(19*20));
	                    	rowHead.createCell(0).setCellValue("序号");
	                    	rowHead.getCell(0).setCellStyle(styleBorder);
	                    	rowHead.createCell(1).setCellValue("产品代码");
	                    	rowHead.getCell(1).setCellStyle(styleBorder);
	                    	rowHead.createCell(2).setCellValue("产品名称");
	                    	rowHead.getCell(2).setCellStyle(styleBorder);
	                    	
	                    	CellRangeAddress region12 = new CellRangeAddress(3,3,(short)3,(short)4);
	                        sheet.addMergedRegion(region12);
	                        rowHead.createCell(3).setCellValue("规格型号");
	                        rowHead.getCell(3).setCellStyle(styleBorder);
	                        rowHead.createCell(5).setCellValue("数量");
	                    	rowHead.getCell(5).setCellStyle(styleBorder);
	                    	rowHead.createCell(6).setCellValue("单位");
	                    	rowHead.getCell(6).setCellStyle(styleBorder);
	                    	rowHead.createCell(7).setCellValue("单价");
	                    	rowHead.getCell(7).setCellStyle(styleBorder);
	                    	rowHead.createCell(8).setCellValue("金额");
	                    	rowHead.getCell(8).setCellStyle(styleBorder);
	                    	rowHead.createCell(9).setCellValue("备注");
	                    	rowHead.getCell(9).setCellStyle(styleBorder);
	                    	
	                    	
	                    	HSSFCellStyle cellStyle = workbook.createCellStyle();
	                    	cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框    
	                    	cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框    
	                    	cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框    
	                    	cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框  
	                    	cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居左
	                    	
	                    	HSSFFont font = workbook.createFont();    
	                    	font.setFontName("宋体");    
	                    	font.setFontHeightInPoints((short)11);//设置字体大小   
	                    	cellStyle.setFont(font);//选择需要用到的字体格式   
	                    	sheet.setDefaultColumnStyle(0, cellStyle);
	                    	sheet.setDefaultColumnStyle(1, cellStyle);
	                    	sheet.setDefaultColumnStyle(2, cellStyle);
	                    	sheet.setDefaultColumnStyle(3, cellStyle);
	                    	sheet.setDefaultColumnStyle(4, cellStyle);
	                    	sheet.setDefaultColumnStyle(5, cellStyle);
	                    	sheet.setDefaultColumnStyle(6, cellStyle);
	                    	sheet.setDefaultColumnStyle(7, cellStyle);
	                    	sheet.setDefaultColumnStyle(8, cellStyle);
	                    	sheet.setDefaultColumnStyle(9, cellStyle);
	                    	sheet.setColumnWidth(0, (short)(4.5*256));
	                    	sheet.setColumnWidth(1, (short)(6.9*356));
	                    	sheet.setColumnWidth(2, (short)(9.83*356));
	                    	sheet.setColumnWidth(3, (short)(7.3*356));
	                    	sheet.setColumnWidth(4, (short)(4.15*356));
	                    	sheet.setColumnWidth(5, (short)(7.85*356));
	                    	sheet.setColumnWidth(6, (short)(7.3*356));
	                    	sheet.setColumnWidth(7, (short)(5.45*356));
	                    	sheet.setColumnWidth(8, (short)(6.4*356));
	                    	sheet.setColumnWidth(9, (short)(8.55*356));
	                    	
	                    	HSSFRow row=null;
	                    	HSSFCell cell=null;
	                    	
	                    	int size=list.size();
	                    	if(size<=12) {
	                    		for(int i=0;i<list.size();i++) {
		                    		row = sheet.createRow(i+4);
		                    		
		                    		row.setHeight((short)(18.75*20));
		                    		row.createCell(0).setCellValue(i+1);
		                            row.createCell(1).setCellValue("00"+list.get(i).get("id").toString());
		                            row.createCell(2).setCellValue(list.get(i).get("name").toString());
		                            CellRangeAddress region10 = new CellRangeAddress(i+4,i+4,(short)3,(short)4);
			                        sheet.addMergedRegion(region10);
		                            row.createCell(3).setCellValue(list.get(i).get("weight").toString());
		                            row.createCell(5).setCellValue(list.get(i).get("num").toString());
		                            row.createCell(6).setCellValue(list.get(i).get("danwei").toString());
		                            row.createCell(7).setCellValue(list.get(i).get("price").toString());
		                            row.createCell(8).setCellValue(list.get(i).get("total").toString());
		                              
		                    	}
	                    		int i=12-size;
	                    		for(int j=0;j<i;j++) {
		                    		row = sheet.createRow(j+4+size);
		                    		
		                    		row.setHeight((short)(18.75*20));
		                    		row.createCell(0).setCellValue(1);
		                            row.createCell(1).setCellValue("");
		                            row.createCell(2).setCellValue("");
		                            CellRangeAddress region11 = new CellRangeAddress(j+4+size,j+4+size,(short)3,(short)4);
			                        sheet.addMergedRegion(region11);
		                            row.createCell(3).setCellValue("");
		                            row.createCell(4).setCellValue("");
		                            row.createCell(5).setCellValue("");
		                            row.createCell(6).setCellValue("");
		                            row.createCell(7).setCellValue("");
		                            row.createCell(8).setCellValue("");
		                              
		                    	}
	                    	}else {
	                    		for(int i=0;i<12;i++) {
		                    		row = sheet.createRow(i+4);
		                    		
		                    		row.setHeight((short)(18.75*20));
		                    		row.createCell(0).setCellValue(i+1);
		                            row.createCell(1).setCellValue(list.get(i).get("price").toString());
		                            row.createCell(2).setCellValue(list.get(i).get("num").toString());
		                            row.createCell(3).setCellValue(list.get(i).get("total").toString());
		                            row.createCell(4).setCellValue(list.get(i).get("name").toString());
		                            row.createCell(5).setCellValue(list.get(i).get("total").toString());
		                            row.createCell(6).setCellValue(list.get(i).get("total").toString());
		                            row.createCell(7).setCellValue(list.get(i).get("total").toString());
		                            row.createCell(8).setCellValue(list.get(i).get("total").toString());
		                              
		                    	}
	                    		int i=size-12;    //创建第二个单
	                    	}
	                    	
	                    	row = sheet.createRow(16);
                    		//row.setHeight((short)(18.75*20));
	                    	CellRangeAddress region5 = new CellRangeAddress(16,16,(short)0,(short)1);
	                        sheet.addMergedRegion(region5);
                    		row.createCell(0).setCellValue("数量合计：");
                    		row.createCell(3).setCellValue("金额合计：");
                    		row.createCell(4).setCellValue("大写：");
                    		row.createCell(7).setCellValue("小写：");
                    		row = sheet.createRow(17);
                    		CellRangeAddress region13 = new CellRangeAddress(17,17,(short)0,(short)1);
	                        sheet.addMergedRegion(region13);
                    		row.createCell(0).setCellValue("制单：");
                    		row.createCell(1).setCellValue("");
                    		row.createCell(2).setCellValue("收款：");
                    		row.createCell(3).setCellValue("");
                    		row.createCell(4).setCellValue("仓管：");
                    		row.createCell(5).setCellValue("");
                    		row.createCell(6).setCellValue("送货人：");
                    		row.createCell(7).setCellValue("");
                    		row.createCell(8).setCellValue("签收：");
                    		row = sheet.createRow(18);
                    		CellRangeAddress region6 = new CellRangeAddress(18,18,(short)0,(short)1);
	                        sheet.addMergedRegion(region6);
                    		row.createCell(0).setCellValue("订货电话：");
                    		row.createCell(1).setCellValue("0752-6666666");
                    		CellRangeAddress region7 = new CellRangeAddress(18,18,(short)3,(short)5);
	                        sheet.addMergedRegion(region7);
                    		row.createCell(3).setCellValue("传真：0752666666");
                    		CellRangeAddress region8 = new CellRangeAddress(18,18,(short)7,(short)9);
	                        sheet.addMergedRegion(region8);
                    		row.createCell(4).setCellValue("投诉电话：00000000");
                    		row = sheet.createRow(19);
                    		CellRangeAddress region9 = new CellRangeAddress(19,20,(short)2,(short)9);
	                        sheet.addMergedRegion(region9);
	                       // CellStyle callStyle = workbook.createCellStyle();
	                       // callStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中  
	                       // callStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
	                        row.createCell(1).setCellValue("备注：");
	                       // row.createCell(1).setCellStyle(callStyle);
	                        CellRangeAddress region10 = new CellRangeAddress(19,20,(short)1,(short)1);
	                        sheet.addMergedRegion(region10);
                    		
                    		
                    		
	                    	
	                         
	                      
	                }
	        		
	    		}
        	}
        	workbook.write(out);
        	//workbook.write(fos);  
            out.flush();  
            out.close();  
            File newFile = new File(realPath, newFileName); 
            // 下载  
            InputStream fis = new BufferedInputStream(new FileInputStream(  
                    newFile));  
            //HttpServletResponse response = ServletActionContext.getResponse();  
            byte[] buffer = new byte[fis.available()];  
            fis.read(buffer);  
            fis.close();  
            response.reset();  
            response.setContentType("text/html;charset=UTF-8");  
            OutputStream toClient = new BufferedOutputStream(  
                    response.getOutputStream());  
            response.setContentType("application/x-msdownload");  
            String newName = URLEncoder.encode(  
                    "送货单" + System.currentTimeMillis() + ".xls",  
                    "UTF-8");  
            response.addHeader("Content-Disposition",  
                    "attachment;filename=\"" + newName + "\"");  
            response.addHeader("Content-Length", "" + newFile.length());  
            toClient.write(buffer);  
            toClient.flush(); 
        } catch (Exception e1) {  
             e1.printStackTrace(); 
		}finally {  
            /*try {  
                if (null != is) {  
                    is.close();  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  */
        }
         
          
        // 删除创建的新文件  
        // this.deleteFile(newFile);  
    }  
	 /**  
     * 复制文件  
     *   
     * @param s  源文件  
     * @param t  复制到的新文件  
     */  
    public void fileChannelCopy(File s, File t) {  
        try {  
            InputStream in = null;  
            OutputStream out = null;  
            try {  
                in = new BufferedInputStream(new FileInputStream(s), 1024);  
                out = new BufferedOutputStream(new FileOutputStream(t), 1024);  
                byte[] buffer = new byte[1024];  
                int len;  
                while ((len = in.read(buffer)) != -1) {  
                    out.write(buffer, 0, len);  
                }  
            } finally {  
                if (null != in) {  
                    in.close();  
                }  
                if (null != out) {  
                    out.close();  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  

    private String getSispPath(HttpServletRequest request) {  
        String classPaths = request.getSession().getServletContext().getRealPath("/uploadFile");
        //String[] aa = classPaths.split("");  
        String sispPath = classPaths.replaceAll("\\\\", "/");  
        /*for (int i = 1; i < aa.length - 2; i++) {  
            sispPath += aa[i] + "/";  
        }*/  
        return sispPath;  
    }  
  
    /**  
     * 读取excel模板，并复制到新文件中供写入和下载  
     *   
     * @return  
     */  
    public File createNewFile(HttpServletRequest request) {  
        // 读取模板，并赋值到新文件************************************************************  
        // 文件模板路径  
        //String path = (getSispPath(request)+"/shdgsA5.xlsx");  
        //File file = new File(path);  
        // 保存文件的路径  
        String realPath = (getSispPath(request) + "/files");  
        // 新的文件名  
        String newFileName = "送货单" + System.currentTimeMillis() + ".xls";  
        // 判断路径是否存在  
        /*File dir = new File(realPath);  
        if (!dir.exists()) {  
            dir.mkdirs();  
        } */ 
        // 写入到新的excel  
        //File newFile = new File(realPath, newFileName);  
        FileOutputStream out = null;
        File newFile=null;
        try {  
        	HSSFWorkbook workbook = new HSSFWorkbook();  
            //添加Worksheet（不添加sheet时生成的xls文件打开时会报错)  
        	HSSFSheet sheet1 = workbook.createSheet("test");    
            //新建文件  
            
          //添加表头  
            HSSFRow row = workbook.getSheetAt(0).createRow(0);    //创建第一行     
            	HSSFCell cell = row.createCell(0);  
                cell.setCellValue("test");  
            out = new FileOutputStream(realPath+"/"+newFileName);  
            workbook.write(out); 
            newFile = new File(realPath, newFileName); 
            //newFile.createNewFile();  
            // 复制模板到新文件  
            //fileChannelCopy(file, newFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }finally {
        	try {    
                out.close();    
            } catch (IOException e) {    
                e.printStackTrace();  
            } 
        }  
        return newFile;  
    }  
    /**  
     * 下载成功后删除  
     *   
     * @param files  
     */  
    private void deleteFile(File... files) {  
        for (File file : files) {  
            if (file.exists()) {  
                file.delete();  
            }  
        }  
    }  
  
	
}
